package com.abcdefg.lotterysystem.common.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.util.Optional;

@Configuration
public class Mail {
    private static final Logger logger = LoggerFactory.getLogger(Mail.class);
    private MailProperties mailProperties;
    private JavaMailSender javaMailSender;

    public Mail(MailProperties mailProperties, JavaMailSender javaMailSender) {
        this.mailProperties = mailProperties;
        this.javaMailSender = javaMailSender;
    }

    public Boolean send(String to, String subject, String content) {

        // 创建⼀个邮件消息
        MimeMessage message = javaMailSender.createMimeMessage();

        // 创建 MimeMessageHelper
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, false);
            // 发件⼈邮箱和名称
            String personal =
                    Optional.ofNullable(mailProperties.getProperties().get("personal"))
                            .orElse(mailProperties.getUsername());
            helper.setFrom(mailProperties.getUsername(), personal);
            // 收件⼈邮箱
            helper.setTo(to);
            // 邮件标题
            helper.setSubject(subject);
            // 邮件正⽂，第⼆个参数表⽰是否是HTML正⽂
            helper.setText(content, true);
            // 发送
            javaMailSender.send(message);
        } catch (Exception e){
            logger.error("向{}发送邮件失败！", to, e);
            return false;
        }
        return true;
    }
}

